﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorkOrder.Business;
using System.Data;
using System.Collections;
using System.Text;

namespace WorkOrder
{
    public partial class workOrder : System.Web.UI.Page
    {
        Business_Table_Work_order b_t_w = new Business_Table_Work_order();
        static DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null || Session["UserID"].ToString() == "")
            {
                Session.Clear();
                ClientScript.RegisterClientScriptBlock(this.GetType(), "windowhref", "<script type='text/javascript'>alert('对不起，您还没有登录系统！');window.parent.location.href='../login.aspx';</script>");
            }
            if (!Page.IsPostBack)
            {
                ddlOrderType.Items.Clear();
                ddlOrderType.DataTextField = "order_type";
                ddlOrderType.DataValueField = "order_type_id";
                ddlOrderType.DataSource = b_t_w.GetOrderType();
                ddlOrderType.DataBind();
                ddlOrderType.Items.Add(new ListItem("-- 请选择 --", "0"));
                ddlOrderType.SelectedIndex = ddlOrderType.Items.Count - 1;

                ddlProduct.Items.Clear();
                ddlProduct.DataTextField = "product_name";
                ddlProduct.DataValueField = "product_id";
                ddlProduct.DataSource = b_t_w.GetProduct();
                ddlProduct.DataBind();
                ddlProduct.Items.Add(new ListItem("-- 请选择 --", "0"));
                ddlProduct.SelectedIndex = ddlProduct.Items.Count - 1;

                ddlStatus.Items.Clear();
                ddlStatus.DataTextField = "order_status";
                ddlStatus.DataValueField = "order_status";
                ddlStatus.DataSource = b_t_w.GetOrderStatus();
                ddlStatus.DataBind();
                ddlStatus.Items.Add(new ListItem("-- 请选择 --", "0"));
                ddlStatus.SelectedIndex = ddlStatus.Items.Count - 1;

                seleTown.Items.Clear();
                seleTown.DataTextField = "town_name";
                seleTown.DataValueField = "town_id";
                seleTown.DataSource = b_t_w.GetTown();
                seleTown.DataBind();
                seleTown.Items.Add(new ListItem("-- 请选择 --", "0"));
                seleTown.SelectedIndex = seleTown.Items.Count - 1;

                seleArea.Items.Clear();
                seleArea.DataTextField = "area_name";
                seleArea.DataValueField = "area_id";
                seleArea.DataSource = b_t_w.GetArea();
                seleArea.DataBind();
                seleArea.Items.Add(new ListItem("-- 请选择 --", "0"));
                seleArea.SelectedIndex = seleArea.Items.Count - 1;

                GridView1.Attributes.Add("SortExpression", "task_time");
                GridView1.Attributes.Add("SortDirection", "DESC");
                txtRow.Text = GridView1.PageSize.ToString();

                dt = null;
            }
        }
        #region 查询数据
        private void BindGridView()
        {
            string sqlstr = "1=1";
            if (!string.IsNullOrEmpty(txtOrderNo.Value.Trim()))
                sqlstr += " and order_number='" + Server.HtmlEncode(txtOrderNo.Value.Trim()) + "'";
            if (!string.IsNullOrEmpty(txtTitle.Text.Trim()))
                sqlstr += " and title like '%" + Server.HtmlEncode(txtTitle.Text.Trim()) + "%'";
            if (ddlProduct.SelectedValue != "0")
                sqlstr += " and product_id=" + ddlProduct.SelectedValue;
            if (ddlOrderType.SelectedValue != "0")
                sqlstr += " and order_type_id=" + ddlOrderType.SelectedValue;
            if (seleTown.Value != "0")
                sqlstr += " and town_id=" + seleTown.Value;
            else if (seleArea.Value != "0")
            {
                ArrayList arr = b_t_w.GetTownIdByArea(seleArea.Value);
                string tmp = "";
                if (arr != null && arr.Count > 0)
                {
                    for (int i = 0; i < arr.Count;i++ )
                        tmp += " or town_id=" + arr[i].ToString();
                }
                sqlstr += " and (" + tmp.Substring(4, tmp.Length - 4) + ")";
            }
            if (ddlStatus.SelectedValue != "0")
                sqlstr += " and order_status='" + ddlStatus.SelectedValue + "'";
            if (seleAccess.Value != "0")
                sqlstr += " and access_mode='" + seleAccess.Value + "'";

            if (txtFinish_start.Value != "" && txtFinish_end.Value != "")
            {
                sqlstr += " and finish_time between '" + txtFinish_start.Value + " 0:0:0' and '" + txtFinish_end.Value + " 23:59:59' and (order_status='已关闭' or order_status='待业务确认')";
            }
                
            if (rblIsBackTrue.Checked)
                sqlstr += " and is_back<>0";
            else if (rblIsBackFalse.Checked)
                sqlstr += " and is_back=0";
                
            if (txtSTART_DATE.Value != "" && txtEND_DATE.Value != "")
                sqlstr += " and task_time between '" + txtSTART_DATE.Value + " 0:0:0' and '" + txtEND_DATE.Value + " 23:59:59'";
            
            if (sqlstr=="1=1")
            {
                GridView1.Visible = false;
                ClientScript.RegisterClientScriptBlock(GetType(), "winowhref", "<script type='text/javascript'>alert('请选择一项查询条件！');</script>");
                return;
            }

            dt = b_t_w.QueryDatas(sqlstr);

            if (dt != null)
                hidRowCount.Value = dt.Rows.Count.ToString();
            lblRowCount.Text = "共&nbsp;" + hidRowCount.Value + "&nbsp;条记录";

            try { GridView1.PageSize = Convert.ToInt32(txtRow.Text.Trim()); }
            catch { }

            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView1.Attributes["SortExpression"];
            string sortDirection = this.GridView1.Attributes["SortDirection"];

            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                if (dt != null)
                    dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }

            // GridView绑定并显示数据
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.Visible = true;
        }
        #endregion

        #region 处理光标行颜色事件
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor,this.style.background='#ffe3a0'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }
        #endregion

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                GridView1.PageIndex = e.NewPageIndex;
                BindGridView();
                TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum"); tb.Text = (GridView1.PageIndex + 1).ToString();
            }
            catch { }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "go")
            {
                try
                {
                    TextBox tb = (TextBox)GridView1.BottomPagerRow.FindControl("inPageNum");
                    int num = Int32.Parse(tb.Text);
                    GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1);
                    GridView1_PageIndexChanging(null, ea);
                }
                catch
                { }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";

            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.GridView1.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }

            // 重新设定GridView排序数据列及排序方向
            GridView1.Attributes["SortExpression"] = sortExpression;
            GridView1.Attributes["SortDirection"] = sortDirection;

            BindGridView();
        }

        #region 查询按钮事件
        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            BindGridView();
        }
        #endregion 

        #region 导出到excel文件
        #region 导出主单
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (dt != null)
            {
                string[] title = { "工单号", "工单主题", "产品类型", "工单类型", "接入模式", "区域", "镇区", "工单状态", "是否退单", "签收人", "派单时间", "签收时间", "需求分析时间", "审核方案时间", "数据配置时间", "CRM确认时间", "完成时间", "退单原因", "退单描述", "集团编码", "用户编码" };
                string[] field = { "order_number", "title", "product_name", "order_type", "access_mode", "area_name", "town_name", "order_status", "is_back", "name_remark", "task_time", "checkIn_time", "analysis_time", "audit_time", "config_time", "confirm_time", "finish_time", "back_reason", "back_comment", "group_code", "customer_code" };
                ExportDsToXls(this.Page, "工单查询", title, field, dt);
            }
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (dt != null)
            {
                string[] title = { "工单号", "工单主题", "产品类型", "工单类型", "接入模式", "区域", "镇区", "工单状态", "是否退单", "签收人", "派单时间", "签收时间", "需求分析时间", "审核方案时间", "数据配置时间", "CRM确认时间", "完成时间", "退单原因", "退单描述", "集团编码", "用户编码" };
                string[] field = { "order_number", "title", "product_name", "order_type", "access_mode", "area_name", "town_name", "order_status", "is_back", "name_remark", "task_time", "checkIn_time", "analysis_time", "audit_time", "config_time", "confirm_time", "finish_time", "back_reason", "back_comment", "group_code", "customer_code" };
                ExportDsToXls(this.Page, "工单查询", title, field, dt);
            }
        }
        #endregion

        /**
        #region 合并导出
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            if (dt!=null && txtSTART_DATE.Value.Trim() != "" && txtEND_DATE.Value.Trim() != "")
            {
                string sqlstr = "1=1";
                if (!string.IsNullOrEmpty(txtOrderNo.Value.Trim()))
                    sqlstr += " and A.order_number='" + Server.HtmlEncode(txtOrderNo.Value.Trim()) + "'";
                if (!string.IsNullOrEmpty(txtTitle.Text.Trim()))
                    sqlstr += " and A.title like '%" + Server.HtmlEncode(txtTitle.Text.Trim()) + "%'";
                if (ddlProduct.SelectedValue != "0")
                    sqlstr += " and A.product_id=" + ddlProduct.SelectedValue;
                if (ddlOrderType.SelectedValue != "0")
                    sqlstr += " and A.order_type_id=" + ddlOrderType.SelectedValue;
                if (seleTown.Value != "0")
                    sqlstr += " and A.town_id=" + seleTown.Value;
                else if (seleArea.Value != "0")
                {
                    ArrayList arr = b_t_w.GetTownIdByArea(seleArea.Value);
                    string tmp = "";
                    if (arr != null && arr.Count > 0)
                    {
                        for (int i = 0; i < arr.Count; i++)
                            tmp += " or A.town_id=" + arr[i].ToString();
                    }

                    sqlstr += " and (" + tmp.Substring(4, tmp.Length - 4) + ")";
                }
                if (ddlStatus.SelectedValue != "0")
                    sqlstr += " and order_status='" + ddlStatus.SelectedValue + "'";
                if (ddlCreator.SelectedValue != "0")
                    sqlstr += " and A.entry_person=" + ddlCreator.SelectedValue;
                
                if (txtFinish_start.Value != "" && txtFinish_end.Value != "")
                {
                    if (rblIsBackTrue.Checked)
                        sqlstr += " and A.is_back<>0 and A.finish_time between '" + txtFinish_start.Value + " 0:0:0' and '" + txtFinish_end.Value + " 23:59:59'";
                    else if (rblIsBackFalse.Checked)
                        sqlstr += " and A.is_back=0 and A.finish_time between '" + txtFinish_start.Value + " 0:0:0' and '" + txtFinish_end.Value + " 23:59:59'";
                    else
                        sqlstr += " and A.finish_time between '" + txtFinish_start.Value + " 0:0:0' and '" + txtFinish_end.Value + " 23:59:59'";
                }
                else
                {
                    if (rblIsBackTrue.Checked)
                        sqlstr += " and A.is_back<>0";
                    else if (rblIsBackFalse.Checked)
                        sqlstr += " and A.is_back=0";
                }
                
                if (txtSTART_DATE.Value != "" && txtEND_DATE.Value != "")
                    sqlstr += " and task_time between '" + txtSTART_DATE.Value + " 0:0:0' and '" + txtEND_DATE.Value + " 23:59:59'";

                sqlstr = "select E.*,D.step_name as 工单环节,B.process as 流程子单,C.dept_name as 处理部门,A.request_time as 派单时间,A.response_time as 回复时间,cast(process_time as varchar(10)) " +
                    "as 处理时长,cast(CASE when response_time is null and (cast(cast(DATEDIFF(\"MINUTE\"," +
                    "request_time,GETDATE()) as float)/60/24 as decimal(10,2))-B.timeout)>0 then " +
                    "(cast(cast(DATEDIFF(\"MINUTE\",request_time,GETDATE()) as float)/60/24 as decimal(10,2))-B.timeout) " +
                    "when response_time is not null and (cast(cast(DATEDIFF(\"MINUTE\"," +
                    "request_time,response_time) as float)/60/24 as decimal(10,2))-B.timeout)>0 then " +
                    "(cast(cast(DATEDIFF(\"MINUTE\",request_time,response_time) as float)/60/24 as decimal(10,2))-B.timeout) " +
                    "end as varchar(10)) as 超时,A.remark as 备注 from Table_Order_record A " +
                    "right join (select A.order_id,A.order_number as 工单号,A.title as 工单主题,B.product_name as 产品类型,C.order_type as 工单类型,D.area_name as 区域,D.town_name as 镇区," +
                    "order_status as 工单状态,case when A.is_back=0 then '否' else '是' end as 是否退单,H.remark as 签收人,A.task_time as 派单时间, A.finish_time as 完成时间 from " +
                    "Table_Work_order as A " +
                    "left join Table_Product as B on A.product_id=B.product_id " +
                    "left join Table_Order_type as C on A.order_type_id=C.order_type_id " +
                    "left join Table_User as H on A.entry_person=H.[user_id] " +
                    "inner join (select M.town_id,M.town_name,N.area_name from Table_Town as M,Table_Area N where M.area_id=N.area_id) as D on A.town_id=D.town_id " +
                    " where " + sqlstr + ") E on E.order_id=A.order_id  " +
                    "order by E.创建时间,工单号 desc,派单时间 asc";

                string[] title = { "工单号", "工单主题", "产品类型", "业务类型", "区域", "镇区", "工单状态", "子单号", "处理部门", "派单时间", "回复时间", "处理时长", "超时", "备注" };
                string[] field = { "工单号", "工单主题", "产品类型", "业务类型", "区域", "镇区", "工单状态", "子单号", "处理部门", "派单时间", "回复时间", "处理时长", "超时", "备注" };
                ExportDsToXls(this.Page, "工单查询-合并子单", title, field, b_t_w.GetDatas(sqlstr));
            }
            else
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "winwhref", "<script type='text/javascript'>alert('请输入需要查询的时间范围！');</script>");
            }
        }
        #endregion
        **
         */

        public static string ExportTable(string[] title, string[] field, DataTable table)
        {
            StringBuilder sb = new StringBuilder();

            //列名
            string tmp = "";
            for (int i = 0; i < title.Length; i++)
            {
                if (i > 0) tmp += "\t";
                tmp += title[i];
            }
            sb.AppendLine(tmp);

            //数据内容
            foreach (DataRow row in table.Rows)
            {
                string str = "";

                for (int j = 0; j < field.Length; j++)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        if (column.ColumnName == field[j])
                        {
                            if (j > 0)
                                str += "\t";
                            if (DBNull.Value.Equals(row[column]))
                                str += "";
                            else if (row[column].ToString() == "False")
                                str += "否";
                            else if (row[column].ToString() == "True")
                                str += "是";
                            else str += row[column].ToString().Replace("\r", " ").Replace("\n", " ");
                        }
                    }
                }
                sb.AppendLine(str);
            }

            return sb.ToString();
        }

        public static void ExportDsToXls(Page page, string fileName, string[] title, string[] field, DataTable table)
        {
            page.Response.Clear();
            page.Response.Buffer = true;
            page.Response.Charset = "GB2312";
            //page.Response.Charset = "UTF-8";
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + System.DateTime.Now.ToString("_yyyyMMddHHmmss") + ".xls");
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            page.Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。 
            page.EnableViewState = false;
            page.Response.Write(ExportTable(title, field, table));
            page.Response.End();
        }
        #endregion 
    }
}
